﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Drawing;

namespace MarioArena.Launcher
{
    public class LoadingPopup : IDisposable {
        private PopupForm popupForm;
        private Form waitingForm;
        private string loadMessage;

        /// <summary>
        /// Creates a LoadingPopup.
        /// </summary>
        /// <param name="originForm">Form that uses and shows this LoadingPopup.</param>
        /// <param name="loadMessage">Message shown on the LoadingPopup.</param>
        public LoadingPopup(Form originForm, string loadMessage) 
        {
            this.waitingForm = originForm;
            this.loadMessage = loadMessage;

            Thread t = new Thread(new ThreadStart(workerThread));
            t.IsBackground = true;
            t.SetApartmentState(ApartmentState.STA);
            t.Start();
        }
        public void Dispose() {
            if (popupForm != null)
                popupForm.Invoke(new MethodInvoker(stopThread));
        }
        private void stopThread() {
            if (popupForm != null)
                popupForm.Close();
        }
        /// <summary>
        /// Shows the Popup on the screen.
        /// </summary>
        private void workerThread() {
            popupForm = new PopupForm();
            popupForm.SetLoadMessage(this.loadMessage);
            popupForm.StartPosition = FormStartPosition.Manual;

            int x = waitingForm.Location.X + ((waitingForm.Width - popupForm.Width) / 2);
            int y = waitingForm.Location.Y + ((waitingForm.Height - popupForm.Height) / 2);
            popupForm.Location = new Point(x, y);

            Application.Run(popupForm);
        }
    }
}
